//
//  HBLoginController.m
//  HeartBeat
//
//  Created by karong on 2023/8/28.
//

#import "HBLoginController.h"
#import <Firebase.h>
#import <FirebaseAuth/FirebaseAuth.h>
#import <AuthenticationServices/AuthenticationServices.h>
#import <GoogleSignIn/GoogleSignIn.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import "HBBaseTabBarController.h"
@import LineSDK;

@interface HBLoginController () <ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>
@property (weak, nonatomic) IBOutlet UIButton *languageBtn;
@property (weak, nonatomic) IBOutlet UILabel *languageLabel;
@property (weak, nonatomic) IBOutlet UIButton *fastLoginBtn;
@property (weak, nonatomic) IBOutlet UIView *appleView;
@property (weak, nonatomic) IBOutlet UIView *appIdView;
@property (weak, nonatomic) IBOutlet UIView *googleView;
@property (weak, nonatomic) IBOutlet UIView *facebookView;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UIButton *checkBoxBtn;
@property (weak, nonatomic) IBOutlet UIButton *skipBtn;
@property (weak, nonatomic) IBOutlet UIView *mainView;
@property (strong, nonatomic) NSString *appleNonce;
@end

@implementation HBLoginController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self layoutView];
    [self layoutLanguage];
}

- (void)styleDidChange {
    self.view.backgroundColor = UIColor.font_white_ffffff;
}

- (void)layoutLanguage {
    NSArray * languageArray = @[@"",@"简体中文", @"English", @"繁体中文", @""];
    NSString * language = languageArray[appConfig.languageType];
    self.languageLabel.text = language;
}

- (void)layoutView {
    if (@available(iOS 13.0, *)) {
        [self createAppleLoginView];
    }
    else {
        [self.appleView removeFromSuperview];
    }
    if (appConfig.startConfig.google_login == 1) {
        self.googleView.hidden = NO;
    }
    else {
        [self.googleView removeFromSuperview];
    }
    if (appConfig.startConfig.facebook_login == 1) {
        self.facebookView.hidden = NO;
    }
    else {
        [self.facebookView removeFromSuperview];
    }
    if (appConfig.startConfig.line_login == 1) {
        self.lineView.hidden = NO;
    }
    else {
        [self.lineView removeFromSuperview];
    }
    self.lineView.hidden = NO;
    [self layoutBottomLabel];
    [self.view uploadLayout];
}

- (void)layoutBottomLabel {
    YYLabel *label = [[YYLabel alloc] init];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    [self.mainView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.checkBoxBtn.mas_right).offset(4);
        make.top.bottom.right.mas_equalTo(self.mainView);
    }];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentCenter;
    style.lineBreakMode = NSLineBreakByWordWrapping;
    NSString *text = WSLocalized(@"點擊登錄表示已同意短劇星《用戶協議》\n《隱私政策》");
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:text
                                                                                 attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12], NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName: UIColor.font_gray_999999}];
    
    NSString *string1 = SF(@"《%@》", WSLocalized(@"用戶協議"));
    NSRange range1 = [text rangeOfString:string1];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range1];
    [attrText setTextHighlightRange:range1 color:UIColor.font_yellow_FFCC00 backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [ViewManager pushWebVCWithUrl:API_HEARTBEAT_AGREEMENT_USER titleStr:WSLocalized(@"用戶協議")inController:self];
    }];
    
    NSString *string2 = SF(@"《%@》", WSLocalized(@"隱私政策"));
    NSRange range2 = [text rangeOfString:string2];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range2];
    [attrText setTextHighlightRange:range2 color:UIColor.font_yellow_FFCC00 backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [ViewManager pushWebVCWithUrl:API_HEARTBEAT_AGREEMENT_PRIVACY titleStr:WSLocalized(@"隱私政策")inController:self];
    }];
    label.attributedText = attrText;
}

- (void)createAppleLoginView {
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDButton *appleIDButton = [[ASAuthorizationAppleIDButton alloc] initWithAuthorizationButtonType:ASAuthorizationAppleIDButtonTypeSignIn authorizationButtonStyle:ASAuthorizationAppleIDButtonStyleBlack];
        appleIDButton.frame = CGRectMake(0, 0, 48, 48);
        appleIDButton.layer.masksToBounds = YES;
        appleIDButton.tag = 10000;
        [appleIDButton addTarget:self action:@selector(appleLoginAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.appIdView addSubview:appleIDButton];

    }
}

- (void)loginRequest {
    WeakSelf
    [HBRequest loginWithSuccess:^(id obj) {
        [HBToast dismiss];
        [weakSelf showMainViewController];
        [HBEvenManager event:@"user_login_submit" evenLogType:(HBEvenLogType_Click)
                  attributes:@{@"user_unique_id":SF(@"%ld", appUserCenter.id),
                               @"login_type":KEmptyStr(appUserCenter.bind_third_info),
                               @"is_success":@"true"}];
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        [HBEvenManager event:@"user_login_submit" evenLogType:(HBEvenLogType_Click)
                  attributes:@{@"user_unique_id":SF(@"%ld", appUserCenter.id),
                               @"login_type":KEmptyStr(appUserCenter.bind_third_info),
                               @"is_success":@"false"}];
    }];
}


//游客登录
- (void)visitorRegist:(NSString *)userName password:(NSString *)password {
    [[FIRAuth auth]signOut:nil];
    [appUserCenter logOut];
    WeakSelf
    [[FIRAuth auth] signInWithEmail:userName
                           password:password
                         completion:^(FIRAuthDataResult * _Nullable authResult,
                                      NSError * _Nullable error) {
        if (error) {
            [HBToast simple:error.localizedDescription];
        }else{
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [weakSelf loginRequest];
            }];
        }
    }];
}

- (void)showMainViewController {
    HBBaseNavigationController * nav = [[HBBaseNavigationController alloc]initWithRootViewController:[HBBaseTabBarController new]];
    nav.navigationBarHidden = YES;
    typedef void (^Animation)(void);
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    window.rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
        [UIView setAnimationsEnabled:oldState];
    };
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:nil];
}

- (IBAction)skipAction:(id)sender {
    if (self.isModel) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else {
        if (appConfig.startConfig.click_to_skip_login && !appUserCenter.isLogin) {
            [HBToast loadingFull];
            NSString *userNameStr = [NSString stringWithFormat:@"%@@HeartbeatNovelsApp.com",[HBUserCenterModel uuid]];
            NSString *password = @"HeartbeatNovelsApp123456";
            [[FIRAuth auth] createUserWithEmail:userNameStr
                                       password:password
                                     completion:^(FIRAuthDataResult * _Nullable authResult,
                                                  NSError * _Nullable error) {
                if (error) {
                    [self visitorRegist:userNameStr password:password];
                }else{
                    FIRUser *user = authResult.user;
                    [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                        appUserCenter.qtoken = token;
                        [self loginRequest];
                    }];
                }
            }];
        }
        else {
            [self showMainViewController];
        }
    }
}

- (IBAction)languageAction:(id)sender {
    [ViewManager showLanguageWithSelectHandle:^(NSInteger integer) {
        [HBAppLanguage setUserLanguageType:integer];
        [self layoutLanguage];
    } inController:self];
}

- (IBAction)fastLoginLoginAction:(id)sender {
    if (!self.checkBoxBtn.selected) {
        [HBToast simple:WSLocalized(@"請先閱讀並同意《用戶協議》，《隱私政策》")];
        return;
    }
    [HBToast loadingFull];
    //#ifdef TEST_ON
//        appUserCenter.id = 100021;
//        appUserCenter.token = @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMDAwMjEsImV4cCI6MTY5OTg2ODU0NX0.V7HZLR19KDG7HEZsLGE6s7eDTFEyD4B7nQIN9kbroyI";
//        [appUserCenter save];
//    [self showMainViewController];
//        return;
    //#endif
    [[FIRAuth auth]signOut:nil];
    [appUserCenter logOut];
    NSString *userNameStr = [NSString stringWithFormat:@"%@@HeartbeatNovelsApp.com",[HBUserCenterModel uuid]];
    NSString *password = @"HeartbeatNovelsApp123456";
            
    [[FIRAuth auth] createUserWithEmail:userNameStr
                               password:password
                             completion:^(FIRAuthDataResult * _Nullable authResult,
                                          NSError * _Nullable error) {
        if (error) {
            [self visitorRegist:userNameStr password:password];
        }else{
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [self loginRequest];
            }];
        }
    }];
    [HBEvenManager event:@"user_login_submit" evenLogType:(HBEvenLogType_Click)
              attributes:@{@"login_type":@"email"}];
}

- (IBAction)appleLoginAction:(id)sender {
    if (!self.checkBoxBtn.selected) {
        [HBToast simple:WSLocalized(@"請先閱讀並同意《用戶協議》，《隱私政策》")];
        return;
    }
    [HBToast loadingFull];
    if (@available(iOS 13.0, *)) {
        self.appleNonce = [HBTool randomNonce:32];
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc]init];
        ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName,ASAuthorizationScopeEmail];
        request.nonce = [HBTool stringBySha256HashingString:self.appleNonce];
        ASAuthorizationController *auth = [[ASAuthorizationController alloc]initWithAuthorizationRequests:@[request]];
        auth.delegate = self;
        auth.presentationContextProvider = self;
        [auth performRequests];
    }
    [HBEvenManager event:@"user_login_submit" evenLogType:(HBEvenLogType_Click)
              attributes:@{@"login_type":@"apple"}];
}



- (IBAction)googleLoginAction:(UIButton *)sender {
    if (!self.checkBoxBtn.selected) {
        [HBToast simple:WSLocalized(@"請先閱讀並同意《用戶協議》，《隱私政策》")];
        return;
    }
    [HBToast loadingFull];
    [[GIDSignIn sharedInstance] signOut];
    GIDConfiguration *config = [[GIDConfiguration alloc] initWithClientID:[FIRApp defaultApp].options.clientID];
    [GIDSignIn.sharedInstance setConfiguration:config];
    [GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable signInResult, NSError * _Nullable error) {
        //error.code != -5 用戶退出
        if(error) {
            [HBToast dismiss];
            if(!signInResult.user && !signInResult.user.profile && error.code != -5) {
                [HBToast simple:SF(@"Login failed\n%@", error.localizedDescription)];
            };
        }
        else {
            [signInResult.user refreshTokensIfNeededWithCompletion:^(GIDGoogleUser * _Nullable user,
                                                                                   NSError * _Nullable error) {
                              if (error) {
                                  NSLog(@"%@", error.localizedDescription);
                              } else {
                                  if (user == nil) {
                                      NSLog(@"signInResult.user is nil");
                                  } else {
                                      NSLog(@"user.userID:%@", user.userID);
                                      NSLog(@"user.idToken.tokenString:%@", user.idToken.tokenString);
                                  }
                              }
                          }];
            FIRAuthCredential *credential = [FIRGoogleAuthProvider credentialWithIDToken:signInResult.user.idToken.tokenString accessToken:signInResult.user.accessToken.tokenString];
            [self signInFirebaseWithCredential:credential accountType:0];
        }
    }];
    [HBEvenManager event:@"user_login_submit" evenLogType:(HBEvenLogType_Click)
              attributes:@{@"login_type":@"google"}];
}

- (IBAction)facebookLoginAction:(UIButton *)sender {
    if (!self.checkBoxBtn.selected) {
        [HBToast simple:WSLocalized(@"請先閱讀並同意《用戶協議》，《隱私政策》")];
        return;
    }
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    [login logOut];
    [login logInWithPermissions:@[@"public_profile", @"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult * _Nullable result, NSError * _Nullable error) {
        if (error) {
            [HBToast simple:SF(@"Login failed\n%@", error.localizedDescription)];
        }
        else if(result.token) {
            [HBToast loading];
            FIRAuthCredential *credential = [FIRFacebookAuthProvider credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
            [self signInFirebaseWithCredential:credential accountType:0];
        }
    }];
    [HBEvenManager event:@"user_login_submit" evenLogType:(HBEvenLogType_Click)
              attributes:@{@"login_type":@"facebook"}];
}

- (IBAction)lineLoginAction:(UIButton *)sender {
    if (!self.checkBoxBtn.selected) {
        [HBToast simple:WSLocalized(@"請先閱讀並同意《用戶協議》，《隱私政策》")];
        return;
    }
    NSSet *permissions = [NSSet setWithObjects:
                              [LineSDKLoginPermission profile],
                              [LineSDKLoginPermission openID],
                              nil];
    [[LineSDKLoginManager sharedManager] loginWithPermissions:permissions inViewController:self completionHandler:^(LineSDKLoginResult *result, NSError *error) {
               if (result) {
                   WeakSelf
                   [HBToast loading];
                   [HBRequest loginLineWithAccess_token:result.accessToken success:^(id obj) {
                       [[FIRAuth auth] signInWithCustomToken:appUserCenter.token completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
                           [weakSelf loginRequest];
                       }];
                   } failed:^(NSURLResponse *response, NSError *error, id responseObject) {
                       
                   }];
                   NSLog(@"User Name: %@", result.userProfile.displayName);
               } else {
                   NSLog(@"Error: %@", error);
               }
           }
     ];
    [HBEvenManager event:@"user_login_submit" evenLogType:(HBEvenLogType_Click)
              attributes:@{@"login_type":@"line"}];
}

#pragma mark - Apple Sign

///代理主要用於展示在哪里
-(ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    return self.view.window;
}

-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    if([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]){
        ASAuthorizationAppleIDCredential *appleIDCredential = (ASAuthorizationAppleIDCredential *)authorization.credential;
        if (appleIDCredential.identityToken == nil) {
            [HBToast simple:@"Unable to fetch identity token."];
            return;
        }
        NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken encoding:NSUTF8StringEncoding];
        if (idToken == nil) {
            [HBToast simple:@"Unable to serialize id token from data"];
            return;
        }
        
        // Initialize a Firebase credential.
        FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"apple.com" IDToken:idToken rawNonce:self.appleNonce];
        [self signInFirebaseWithCredential:credential accountType:0];
    }
}

///回调失敗
-(void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = WSLocalized(@"用戶取消了授權請求");
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = WSLocalized(@"授權請求失敗");
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = WSLocalized(@"授權請求響應無效");
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = WSLocalized(@"未能處理授權請求");
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = WSLocalized(@"授權請求失敗未知原因");
            break;
    }
    [HBToast simple:errorMsg];
}

- (void)signInFirebaseWithCredential:(FIRAuthCredential *)credential accountType:(NSInteger)accountType {
    [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
        if (error || !authResult.user) {
            [HBToast simple:error.localizedDescription];
        }
        else {
            NSString *avator;
            if (authResult.user.photoURL) {
                avator = authResult.user.photoURL.absoluteString;
            }
            FIRUser *user = authResult.user;
            [user getIDTokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
                appUserCenter.qtoken = token;
                [self loginRequest];
            }];
            
        }
    }];
}

- (IBAction)checkBoxAction:(UIButton *)sender {
    sender.selected = !sender.selected;
}

@end
